package org.jdsm.flow.gxt.users.client;

import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestTimeoutException;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;

/**
 * Created by IntelliJ IDEA.
 * User: mikom
 * Date: 12.03.11
 * Time: 22:32
 */
public abstract class RequestCallbackSender implements RequestCallback {
    private static final int STATUS_CODE_OK = 200;
    private JSONValue jsonData = null;



    public void onError(Request request, Throwable exception) {
        if (exception instanceof RequestTimeoutException) {
            // handle a request timeout
            errorTimeOut();
        } else {
            // handle other request errors
            error();
        }
    }

    public void onResponseReceived(Request request, Response response) {
        if (STATUS_CODE_OK == response.getStatusCode()) {
            // handle OK response from the server
            jsonData = JSONParser.parseStrict(response.getText());
            success();
        } else {
            // handle non-OK response from the server
            serverIncorrectStatusCode();
        }
    }

    public boolean isSuccessRequest(){
        return jsonData != null;
    }

    public abstract void errorTimeOut();
    public abstract void error();
    public abstract void success();
    public abstract void serverIncorrectStatusCode();

    protected String getResponseText(){
        if(jsonData == null) return "";
        return jsonData.toString();
    }
    public JSONValue getJSONResult(){
         return jsonData;
    }
}
